package cn.zhaoguang.usedcar.main.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.zhaoguang.usedcar.common.constant.PlatformConstants;
import cn.zhaoguang.usedcar.common.http.ResultVO;
import cn.zhaoguang.usedcar.common.util.JwtTokenUtil;
import cn.zhaoguang.usedcar.common.util.PasswordUtil;
import cn.zhaoguang.usedcar.main.entity.Manager;
import cn.zhaoguang.usedcar.main.entity.Seller;
import cn.zhaoguang.usedcar.main.entity.User;
import cn.zhaoguang.usedcar.main.entity.vo.ManagerLoginVO;
import cn.zhaoguang.usedcar.main.entity.vo.SellerLoginVO;
import cn.zhaoguang.usedcar.main.entity.vo.UserLoginVO;
import cn.zhaoguang.usedcar.main.service.ManagerService;
import cn.zhaoguang.usedcar.main.service.SellerService;
import cn.zhaoguang.usedcar.main.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * @Description
 * @Author zhaoguang
 * @Date 2021/7/3 16:45
 */
@RestController
@Api(tags = "登录控制器")
public class LoginController {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private SellerService sellerService;

    @Autowired
    private UserService userService;

    @Autowired
    private ManagerService managerService;

    @GetMapping("/captcha")
    @ApiOperation(value = "验证码", notes = "验证码")
    public void captcha(HttpServletResponse response, HttpSession session) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰线宽度
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(116, 36, 4, 5);
        //得到code
        String code = captcha.getCode();
        System.out.println("验证码：" + code);
        //放到session
        session.setAttribute("code", code);

        ServletOutputStream outputStream = response.getOutputStream();   //输出流
        captcha.write(outputStream);   //读写输出流
        outputStream.close();   //关闭输出流r
    }

    @PostMapping("/seller/login")
    @ApiOperation(value = "商家登录", notes = "商家登录")
    public ResultVO shopLogin(@RequestBody Map<String, String> map) {

        Seller seller = sellerService.findSellerByPhone(map.get("phone"));
        if (seller == null) {
            return ResultVO.error("账号或密码不正确");
        }
        if (!PasswordUtil.matches(seller.getEncryptSalt(), map.get("password"), seller.getPassword())) {
            return ResultVO.error("账号或密码不正确");
        }

        //添加前缀
        StringBuffer sb = new StringBuffer(seller.getPhone());
        sb.insert(0, PlatformConstants.SHOP.getPrefix());
        //生成Token并添加到缓存
        String token = jwtTokenUtil.generateToken(sb.toString());

        SellerLoginVO s = new SellerLoginVO();
        //设置Token返回给前端
        s.setToken(token);
        BeanUtil.copyProperties(seller, s);
        return ResultVO.success("登录成功", s);
    }

    @PostMapping("/seller/logout")
    @ApiOperation(value = "商家退出登录", notes = "商家退出登录")
    public ResultVO shopLogout(@RequestBody Map<String, Integer> map) {
        Integer id = map.get("id");
        Seller seller = sellerService.findSellerById(id);
        if (ObjectUtil.isNotEmpty(seller)) {
            boolean res = jwtTokenUtil.removeToken(PlatformConstants.SHOP.getPrefix() + seller.getPhone());
            if (res) {
                return ResultVO.success("退出成功");
            }
            return ResultVO.error("退出失败");
        }
        return ResultVO.error("退出失败，没有此用户");
    }


    @PostMapping("/user/login")
    @ApiOperation(value = "用户登录", notes = "用户登录")
    public ResultVO userLogin(@RequestBody Map<String, String> map) {

        User user = userService.findUserByPhone(map.get("phone"));
        if (user == null) {
            return ResultVO.error("账号或密码不正确");
        }
        if (!PasswordUtil.matches(user.getEncryptSalt(), map.get("password"), user.getPassword())) {
            return ResultVO.error("账号或密码不正确");
        }

        //添加前缀
        StringBuffer sb = new StringBuffer(user.getPhone());
        sb.insert(0, PlatformConstants.USER.getPrefix());
        //生成Token并添加到缓存
        String token = jwtTokenUtil.generateToken(sb.toString());

        UserLoginVO u = new UserLoginVO();
        //设置Token返回给前端
        u.setToken(token);
        BeanUtil.copyProperties(user, u);
        return ResultVO.success("登录成功", u);
    }

    @PostMapping("/user/logout")
    @ApiOperation(value = "用户退出登录", notes = "用户退出登录")
    public ResultVO userLogout(@RequestBody Map<String, Integer> map) {
        Integer id = map.get("id");
        User user = userService.findUserById(id);
        if (ObjectUtil.isNotEmpty(user)) {
            boolean res = jwtTokenUtil.removeToken(PlatformConstants.USER.getPrefix() + user.getPhone());
            if (res) {
                return ResultVO.success("退出成功");
            }
            return ResultVO.error("退出失败");
        }
        return ResultVO.error("退出失败，没有此用户");
    }


    @PostMapping("/manager/login")
    @ApiOperation(value = "管理员登录", notes = "管理员登录")
    public ResultVO managerLogin(@RequestBody Map<String, String> map) {

        Manager manager = managerService.findManagerByUsername(map.get("username"));
        if (manager == null) {
            return ResultVO.error("用户名或密码不正确");
        }
        if (!PasswordUtil.matches(manager.getEncryptSalt(), map.get("password"), manager.getPassword())) {
            return ResultVO.error("用户名或密码不正确");
        }

        //添加前缀
        String username = manager.getUsername();
        StringBuffer sb = new StringBuffer(username);
        sb.insert(0, PlatformConstants.MANAGE.getPrefix());
        //生成Token
        String token = jwtTokenUtil.generateToken(sb.toString());

        ManagerLoginVO m = new ManagerLoginVO();
        //设置Token返回给前端
        m.setToken(token);
        BeanUtil.copyProperties(manager, m);
        return ResultVO.success("登录成功", m);
    }

    @PostMapping("/manager/logout")
    @ApiOperation(value = "管理员退出登录", notes = "管理员退出登录")
    public ResultVO managerLogout(@RequestBody Map<String, Integer> map) {
        Integer id = map.get("id");
        Manager manager = managerService.findManagerById(id);
        if (ObjectUtil.isNotEmpty(manager)) {
            boolean res = jwtTokenUtil.removeToken(PlatformConstants.MANAGE.getPrefix() + manager.getUsername());
            if (res) {
                return ResultVO.success("退出成功");
            }
            return ResultVO.success("退出失败");
        }
        return ResultVO.success("退出失败，没有此用户");
    }
}
